package com.markhsiu.minimq.remote.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.markhsiu.minimq.channel.ChannelProcessor;
import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.message.constant.MessageSourceEnum;

/**
 * 消费者连接消息处理器
 *  推送消息到消费者和接受消费者发送的消息
 * @author Mark Hsiu
 *
 */
public class CustomerMessageProcessor extends AbstractMessageProcessor{
	private static Logger logger = LoggerFactory.getLogger(CustomerMessageProcessor.class);
	private static boolean isInfoEnabled = logger.isInfoEnabled();
	 
	@Override
	public void handler(final Message request,ChannelProcessor<Message> channel) {
		if(!checkMassage(request)){
			channel.writeAndFlush(Message.newError(request));
			return;
		}
		
		Message response = Message.newSuccess(request);
		response.setSource(MessageSourceEnum.BROKER);
		response.setTarget(MessageSourceEnum.CUSTOMER);
		
		String consumerID = request.getConsumerID();
		boolean flag =  true;
		switch (request.getCmd()) {
			case SUCCESS:
				if(isInfoEnabled){
					logger.info("消费者注册 ：{}", consumerID);
				}
				logger.info("消费者接受消息成功：{}", consumerID );
				return;
			case FAIL:
				if(isInfoEnabled){
					logger.info("消息推送失败！{}", consumerID);
				}
				
				return;
			default:
				response = Message.newFail(request);
				break;
		} 
		
		if(!flag){
			response = Message.newFail(request);
		}
		if(isInfoEnabled){
			logger.info("消费者注册 ：{}", consumerID);
		}
		
		channel.writeAndFlush(response);
	}

}
